Page({
  /**
   * 页面的初始数据
   */
  data: {
    totalMembers: 0,
    groupCount: 0,
    groups: [],
    groupNames: [],
    planId: '',
    status: 'waiting',
    statusText: '等待加入',
    creator: {
      nickName: '',
      avatarUrl: ''
    },
    isLoggedIn: true,
    fromShare: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const app = getApp()
    
    // 保存 planId，供后续使用
    if (options.planId) {
      this.setData({ planId: options.planId })
    }
    
    // 检查全局登录状态
    const userInfo = app.globalData.userInfo || wx.getStorageSync('userInfo')
    if (!userInfo || !userInfo.nickName || !userInfo.avatarUrl) {
      this.setData({ 
        isLoggedIn: false,
        fromShare: options.fromShare || false  // 记录是否来自分享
      })
      return
    }
    
    let plan
    if (options.planId) {
      plan = app.globalData.plans.find(p => p.id === options.planId)
      
      // 如果是从分享链接进入，且状态是等待加入，检查是否已加入
      if (options.fromShare && plan?.status === 'waiting') {
        const hasJoined = plan.members.some(m => 
          m.nickName === userInfo.nickName && m.avatarUrl === userInfo.avatarUrl
        )
        if (!hasJoined) {
          // 如果未加入，则加入分组
          this.joinGroup(plan)
        }
      }
    } else {
      plan = app.globalData.currentPlan
    }

    if (plan) {
      this.setData({
        totalMembers: plan.totalMembers,
        groupCount: plan.groupCount,
        groupNames: plan.groupNames,
        groups: this.processGroupData(plan),
        status: plan.status,
        creator: plan.creatorInfo || {
          nickName: plan.creator || '未知用户',
          avatarUrl: '/images/default-avatar.png'
        },
        isCreator: plan.creator === userInfo.nickName
      })
      this.updateStatusText(plan.status)
    }

    wx.setNavigationBarColor({
      frontColor: '#ffffff',
      backgroundColor: '#3498db'
    });
  },

  processGroupData(plan) {
    return plan.groupNames.map((name, index) => ({
      name,
      members: plan.members.filter(m => m.groupIndex === index)
    }))
  },

  onReady() {},
  onShow() {},
  onHide() {},

  onUnload() {
    if (this.data.watcher) {
      this.data.watcher.close()
    }
  },

  onPullDownRefresh() {},
  onReachBottom() {},

  /**
   * 用户点击右上角或分享按钮时触发
   */
  onShareAppMessage() {
    const { totalMembers, groupCount, groupNames = [] } = this.data
    let shareTitle = `邀请你加入${totalMembers}人${groupCount}组的篮球分组`
    
    if (groupNames && groupNames.length > 0) {
      const groupNamesText = groupNames.slice(0, 2).join('、') + (groupNames.length > 2 ? '等' : '')
      shareTitle += ` (${groupNamesText}组)`
    }
    
    return {
      title: shareTitle,
      path: `/pages/result/result?planId=${this.data.planId}&fromShare=true`,
      imageUrl: '/images/share-bg.png'
    }
  },

  onShareTimeline() {
    const { totalMembers, groupCount, groupNames = [] } = this.data
    let shareTitle = `邀请你加入${totalMembers}人${groupCount}组的篮球分组`
    
    if (groupNames && groupNames.length > 0) {
      const groupNamesText = groupNames.slice(0, 2).join('、') + (groupNames.length > 2 ? '等' : '')
      shareTitle += ` (${groupNamesText}组)`
    }
    
    return {
      title: shareTitle,
      query: `planId=${this.data.planId}`,
      imageUrl: '/images/share-bg.png'
    }
  },

  shareGroup() {
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    })
  },

  watchPlanChanges(planId) {
    const db = wx.cloud.database()
    const watcher = db.collection('groups')
      .doc(planId)
      .watch({
        onChange: (snapshot) => {
          if (snapshot.type === 'init' || snapshot.type === 'update') {
            const plan = snapshot.docs[0]
            this.setData({
              totalMembers: plan.totalMembers,
              groupCount: plan.groupCount,
              groups: this.processGroupData(plan),
              isCreator: plan.creator === getApp().globalData.openId
            })
          }
        },
        onError: (err) => {
          console.error('监听计划变化失败', err)
        }
      })
    
    this.setData({ watcher })
  },

  // 加入分组
  async joinGroup(plan) {
    const app = getApp()
    
    try {
      const userInfo = app.globalData.userInfo
      if (!userInfo) {
        throw new Error('未登录')
      }

      // 随机分配到一个组
      const groupIndex = Math.floor(Math.random() * plan.groupCount)
      
      // 添加成员
      const newMember = {
        nickName: userInfo.nickName,
        avatarUrl: userInfo.avatarUrl,
        joinTime: new Date().toISOString(),
        groupIndex
      }
      
      plan.members.push(newMember)

      // 更新全局数据
      if (!app.globalData.plans.find(p => p.id === plan.id)) {
        app.globalData.plans.push(plan)
      }
      app.savePlans()
      
      // 更新显示
      this.setData({
        groups: this.processGroupData(plan)
      })

      // 显示加入成功提示
      wx.showToast({
        title: `已加入${plan.groupNames[groupIndex]}组`,
        icon: 'success',
        duration: 2000
      })
    } catch (err) {
      console.error('加入分组失败', err)
      wx.showToast({
        title: '加入失败，请重试',
        icon: 'none'
      })
    }
  },

  // 更新状态文本
  updateStatusText(status) {
    const statusMap = {
      'waiting': '等待加入',
      'started': '分组进行中',
      'completed': '已结束'
    }
    this.setData({
      status,
      statusText: statusMap[status] || '未知状态'
    })
  },

  // 处理登录
  async handleLogin() {
    try {
      const { userInfo } = await wx.getUserProfile({
        desc: '用于显示分组信息'
      })

      // 保存用户信息到全局和本地存储
      const app = getApp()
      app.globalData.userInfo = userInfo
      wx.setStorageSync('userInfo', userInfo)

      // 更新登录状态
      this.setData({ isLoggedIn: true })
      
      // 如果是从分享链接进入，直接加入分组
      if (this.data.fromShare) {
        const plan = app.globalData.plans.find(p => p.id === this.data.planId)
        if (plan && plan.status === 'waiting') {
          const hasJoined = plan.members.some(m => 
            m.nickName === userInfo.nickName && m.avatarUrl === userInfo.avatarUrl
          )
          if (!hasJoined) {
            await this.joinGroup(plan)
          }
        }
      }
      
      // 重新加载页面数据
      this.onLoad({ 
        planId: this.data.planId,
        fromShare: this.data.fromShare 
      })
    } catch (err) {
      console.error('登录失败', err)
      wx.showToast({
        title: '需要授权才能参与分组',
        icon: 'none',
        duration: 2000
      })
    }
  }
})